import MapBoxGL from '!./mapbox/mapbox-gl';
import * as turf from '@turf/turf';

class ThreeMap {

    constructor(container, style, center = [118, 37], zoom = 10, pitch = 0) {

        this.map = new MapBoxGL.Map({
            container,
            style,
            center,
            zoom,
            pitch,
            antialias: true
        })
    }

    addMarker(markerData, callback) {

        let {elHTML, lngLat} = markerData;

        if (lngLat === undefined) return;

        let marker;

        if (elHTML !== undefined) {

            let el = document.createElement('div');
            el.innerHTML = elHTML;

            marker = new MapBoxGL.Marker(el).setLngLat(lngLat).addTo(this.map);

        } else {

            marker = new MapBoxGL.Marker().setLngLat(lngLat).addTo(this.map);
        }

        if (callback !== undefined) callback(marker);
    }

    addPopup(popupData, callback) {

        let {elHTML, lngLat, offset} = popupData;

        if (lngLat === undefined || elHTML === undefined) return;

        let popup = new MapBoxGL.Popup({
            closeButton: false,
            closeOnClick: false,
            offset: offset
        });

        let el = document.createElement('div');
        el.innerHTML = elHTML;

        popup.setDOMContent(el).setLngLat(lngLat).addTo(this.map);

        if (callback !== undefined) callback(popup);
    }

    /**
     * 计算沿线位置点
     * @param points 经纬度数组
     * @param distance 距离首端点距离公里
     * @returns GeoJSON的Feature
     */
    getPointAt(points, distance) {

        let line = turf.lineString([points]);
        let options = {units: 'kilometers'};

        return  turf.along(line, distance, options);
    }
}

export default ThreeMap